package com.hyjiacan.apps.audionly.ui

import android.content.Intent
import android.os.Bundle
import android.Manifest
import android.content.pm.PackageManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.hyjiacan.apps.audionly.R
import com.hyjiacan.apps.audionly.databinding.ActivityParamSettingBinding
import com.hyjiacan.apps.audionly.ui.viewmodel.ParamViewModel

/**
 * 参数设置界面Activity
 */
class ParamSettingActivity : AppCompatActivity() {
    private lateinit var binding: ActivityParamSettingBinding
    private lateinit var viewModel: ParamViewModel
    private var videoPath: String? = null

    companion object {
        private const val STORAGE_PERMISSION_REQUEST_CODE = 100
        private const val DIRECTORY_CHOOSER_REQUEST_CODE = 101
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_param_setting)

        // 初始化ViewModel
        viewModel = ViewModelProvider(this).get(ParamViewModel::class.java)
        binding.viewModel = viewModel
        binding.lifecycleOwner = this

        // 从Intent获取视频文件路径
        videoPath = intent.getStringExtra("video_path")
        videoPath?.let {
            viewModel.setVideoPath(it)
        }



        // 设置存储目录选择按钮点击事件
        binding.selectDirBtn.setOnClickListener {
            // 检查是否有存储权限
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                // 请求权限
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    STORAGE_PERMISSION_REQUEST_CODE
                )
            } else {
                // 已有权限，打开目录选择器
                openDirectoryChooser()
            }
        }

        // 设置提取按钮点击事件
        binding.extractBtn.setOnClickListener {
            // 导航到提取进度界面
            val intent = Intent(this, ExtractProgressActivity::class.java)
            intent.putExtra("audio_format", viewModel.selectedFormat.value)
            intent.putExtra("audio_bitrate", viewModel.selectedBitrate.value)
            intent.putExtra("output_filename", viewModel.outputFilename.value)
            intent.putExtra("video_path", videoPath)
            intent.putExtra("custom_storage_path", viewModel.getCurrentStoragePath())
            startActivity(intent)
        }

        // 初始化显示存储路径
        updateStoragePathDisplay(viewModel.getCurrentStoragePath() ?: "默认存储路径")

        // 设置格式选择监听器
        binding.formatRadioGroup.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.mp3_radio -> viewModel.setFormat("mp3")
                R.id.aac_radio -> viewModel.setFormat("aac")
            }
        }

        // 设置比特率选择监听器
        binding.bitrateRadioGroup.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.bitrate_128 -> viewModel.setBitrate(128)
                R.id.bitrate_192 -> viewModel.setBitrate(192)
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == STORAGE_PERMISSION_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，打开目录选择器
                openDirectoryChooser()
            } else {
                // 权限被拒绝
                Toast.makeText(this, "需要存储权限才能选择自定义目录", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun openDirectoryChooser() {
        // 这里实现打开目录选择器的逻辑
        // 注意：Android没有内置的目录选择器，需要使用第三方库或自定义实现
        // 这里只是一个示例
        Toast.makeText(this, "打开目录选择器", Toast.LENGTH_SHORT).show()
        // 实际应用中，你可以使用Intent.ACTION_OPEN_DOCUMENT_TREE或第三方库
    }

    private fun updateStoragePathDisplay(path: String) {
        // 更新UI显示当前存储路径
        binding.storagePathText.text = "当前存储路径: $path"
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DIRECTORY_CHOOSER_REQUEST_CODE && resultCode == RESULT_OK) {
            // 处理选择的目录
            data?.data?.let {
                // 获取选择的目录路径
                val path = it.path ?: ""
                // 更新ViewModel中的存储路径
                viewModel.setCustomStoragePath(path)
                // 更新UI显示
                updateStoragePathDisplay(path)
            }
        }
    }

    init {
        // 注册ActivityResultContracts
        // 在实际应用中，你需要使用Activity Result API来处理目录选择
    }
}
